// 法一
// var events = require("events");
// var Emitter = events.EventEmitter;

// function Dog(name,energy){
//     Emitter.call(this);
//     this.name = name;
//     this.energy = energy;
// }

// Dog.prototype = Emitter.prototype;

// Dog.prototype.bark = function() {
//     console.log(this.name + " bark! energy: " + this.energy);
//     this.energy--;
// }

// module.exports = Dog;


// 法2
var events = require("events");
var EventEmitter = events.EventEmitter;

function Dog(name, energy){
    EventEmitter.call(this);
    this.name = name;
    this.energy = energy;
    /**
     * function 函数，函数内this指向取决于调用主体
     * 箭头函数，函数内this指向函数定义得上下文
     */
    //this.that = this; //如果是在搞不清就用that，下面无论是function()还是箭头函数都用that代替
    var intervalId = setInterval( ()=>{ //箭头函数,this取决于上下文位置；function()取决于谁调用它
        console.log(this);
        if(this.energy >= 0){
            this.emit("bark");
            this.energy--;
        }
        else{
            clearInterval(intervalId);
        }
    }, 1000)
}

for(var i in EventEmitter.prototype) { //遍历对象的属性
    Dog.prototype[i] = EventEmitter.prototype[i];
}
module.exports = Dog;